package com.example.p2p;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Receive {

    public static void main(String[] args) throws IOException {
        String msg = "Hello";
        InetAddress group = InetAddress.getByName("228.5.6.7");
        MulticastSocket s = new MulticastSocket(6789);
        //加入多播组
        s.joinGroup(group);
        //开辟接收缓冲区　　
        byte[] buf = new byte[10];
        // 创建接收数据报
        DatagramPacket recv = new DatagramPacket(buf, buf.length);
        //接收
        while(true){
            s.receive(recv);
            byte[] src = recv.getData();
            byte[] tar = new byte[recv.getLength()];
            System.arraycopy(src,0,tar,0,tar.length);
            String data = new String(tar, StandardCharsets.UTF_8);
            System.out.println("data:"+data);
        }
    }
}
